package cn.yunyichina.provider.base.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.fastjson.JSONObject;

import cn.yunyichina.provider.framework.mvc.dao.BaseDao;
import cn.yunyichina.provider.framework.page.PageInfo;
import cn.yunyichina.utils.convert.JsonUtils;

/**
 * 基础Service功能
 */
public class BaseSelectService {
	private static final Logger logger = LoggerFactory.getLogger(BaseSelectService.class);
	
	/**
	 * 通用解析-组装类型的列表查询
	 * @param strJson
	 * @param clz
	 * @param dao
	 * @return
	 */
	public <T> List<T> listEntity(String strJson,Class<T> clz,BaseDao<T> dao) {
		logger.debug("listEntity入参:" + strJson);
		JSONObject jsonObj = JsonUtils.parseObject(strJson);
		T entity = JsonUtils.parseObject(strJson, clz);

		PageInfo pageInfo = null;
		if (jsonObj.containsKey("pageInfo")) {
			pageInfo = JsonUtils.parseObject(jsonObj.getJSONObject("page_info"), PageInfo.class);
		} else {
			pageInfo = new PageInfo();
		}
		List<String> orderColumns = null;
		if (jsonObj.containsKey("orderColumns") && StringUtils.isNotEmpty(jsonObj.getString("orderColumns"))) {
			orderColumns = new ArrayList<String>();
			String str = jsonObj.getString("orderColumns");
			if (str.startsWith("[")) {
				str = str.substring(1);
			}
			if (str.endsWith("]")) {
				str = str.substring(0,str.length() - 1);
			}
			String[] listObj = str.split(",");
			for (Object field : listObj) {
				orderColumns.add((String) field);
			}
		}

		List<String> selects = null;
		if (jsonObj.containsKey("selects") && StringUtils.isNotEmpty(jsonObj.getString("selects"))) {
			selects = new ArrayList<String>();
			String str = jsonObj.getString("selects");
			if (str.startsWith("[")) {
				str = str.substring(1);
			}
			if (str.endsWith("]")) {
				str = str.substring(0,str.length() - 1);
			}
			String[] listObj = str.split(",");
			for (Object field : listObj) {
				selects.add((String) field);
			}
		}


		List<T> list = dao.select(entity, selects, orderColumns, null, pageInfo);

		logger.debug("listEntity：" + JsonUtils.toJsonString(list));

		return list;

	}

}
